<?php

class Webmix_BlockController extends Core_Controller_Action_Standard
{

  public function indexAction()
  {
    $this->view->someVar = 'someVal';
  }

  public function createAction()
  {   
    if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}   
    //get webmix_id
    $webmix_id = $this->_getParam('webmix');
    //get block position
    $pos_x = $this->_getParam('x');
    $pos_y = $this->_getParam('y');
    $backgound = $this->_getParam('backg','green');
     $viewer = Engine_Api::_()->user()->getViewer();
    // Insert new row after get company_id
    if($this->_getParam('company_id')){
        
        $company_id = $this->_getParam('company_id');

        
        //get photo_id
        $company = Engine_Api::_()->getItem('webmix_company',$company_id);
        $photo_id = $company->photo_id;
        
        $table = Engine_Api::_()->getDbtable('blocks','webmix');
        $db = $table->getAdapter();
        $db->beginTransaction();
        try{
            $block = $table->createRow();
            $block->company_id = $company_id;
            $block->webmix_id = $webmix_id;
            $block->position_x = $pos_x;
            $block->position_y = $pos_y;
            $block->owner_id = $viewer->getIdentity();
            $block->photo_id = $photo_id;
            $block->backgound = $backgound;
            
            $block->save();
            $db->commit();
            
            //Call hook to set company add count
            $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCompanyAddCount', array(
              'company_create' => $company_id,
            ));
            
        }
        catch(Exception $e)
        {
            $db->rollBack();
            throw $e;
        }
        
        $format = $this->_getParam('format','');
        if($format=='smoothbox'){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 10,
       	        'parentRefresh' => 10,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Add block to webmix has been successfully!'))
       	    ));
        }
        $admin = $this->_getParam('a',0);
        
        if(!empty($admin) && $viewer->isAdmin()){
        
            return $this->_helper->redirector->gotoRoute(array('action' => 'edit','controller'=>'webmix','module'=>'webmix','webmix_id' => $webmix_id), 'admin_default', true);
        }
        return $this->_helper->redirector->gotoRoute(array('action' => 'index','controller'=>'index','module'=>'webmix','webmix' => $webmix_id), 'default', true);
        return $this->redirect('index','index','webmix',array('webmix'=>$webmix_id));
    } 
    
    if($this->_getParam('musicalbum_id')){
        
        $company_id = $this->_getParam('musicalbum_id');

        
        //get photo_id
        $company = Engine_Api::_()->getItem('webmix_musicalbum',$company_id);
        $photo_id = $company->photo_id;
        
        $table = Engine_Api::_()->getDbtable('blocks','webmix');
        $db = $table->getAdapter();
        $db->beginTransaction();
        try{
            $block = $table->createRow();
            $block->company_id = $company_id;
            $block->webmix_id = $webmix_id;
            $block->position_x = $pos_x;
            $block->position_y = $pos_y;
            $block->owner_id = $viewer->getIdentity();
            $block->photo_id = $photo_id;
            $block->backgound = $backgound;
            
            if(empty($company->add_count )) {
                $company->add_count = 1;
            }
            else {
                $company->add_count = $company->add_count +1;
            }
            
            $company->save();
            $block->save();
            $db->commit();
            
            
            
        }
        catch(Exception $e)
        {
            $db->rollBack();
            throw $e;
        }
        
        $format = $this->_getParam('format','');
        if($format=='smoothbox'){
            return $this->_forward('success', 'utility', 'core', array(
       	        'smoothboxClose' => 10,
       	        'parentRefresh' => 10,
       	        'messages' => array(Zend_Registry::get('Zend_Translate')->_('Add block to webmix has been successfully!'))
       	    ));
        }
        $admin = $this->_getParam('a',0);
        
        if(!empty($admin) && $viewer->isAdmin()){
        
            return $this->_helper->redirector->gotoRoute(array('action' => 'edit','controller'=>'webmix','module'=>'webmix','webmix_id' => $webmix_id), 'admin_default', true);
        }
        return $this->_helper->redirector->gotoRoute(array('action' => 'index','controller'=>'index','module'=>'webmix','webmix' => $webmix_id), 'default', true);
        return $this->redirect('index','index','webmix',array('webmix'=>$webmix_id));
    } 
    $admin = $this->_getParam('a',0);  
    
    $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
    if ($webmix && $webmix->content_type == Webmix_Api_Core::WEBMIX_CONTENT_TYPE_MUSIC){
        return $this->_forward('create','album','webmix',array('action_type'=>'block_create','webmix'=>$webmix_id,'x'=>$pos_x,'y'=>$pos_y,'a'=>$admin));
    }
    else {
       return $this->_forward('create','company','webmix',array('action_type'=>'block_create','webmix'=>$webmix_id,'x'=>$pos_x,'y'=>$pos_y,'a'=>$admin));
    }
    
  }
  
  public function editAction()
  {
        if( !$this->_helper->requireUser()->isValid() ) {
        		return;
        	}   
         $webmix_id = $this->_getParam('webmix',null);
         $block_id = $this->_getParam('block',null);   
         $viewer = Engine_Api::_()->user()->getViewer();  
         $this->view->form = $form = new Webmix_Form_Block_Edit(array('block'=>$block_id,'webmix'=>$webmix_id));
        
        $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
        $this->view->content_type = $webmix->content_type;
        if ($webmix->content_type == Webmix_Api_Core::WEBMIX_CONTENT_TYPE_MUSIC){
            $this->view->form = $form = new Webmix_Form_Album_Create();
        }
        
        $this->view->webmix_id = $webmix_id;
        // Check post
        if(!$this->getRequest()->isPost()){
            return;
        }
        if (!isset($_POST['key']) || empty($_POST["key"])){
           $form->addError('Your artist name not found.');
           return;
        } 
    
        // Check form validate
        if(!$form->isValid($this->getRequest()->getPost())){
            return;
        }
        
        $values = $form->getValues();
        $company_id = $values['comp_id'];
        
        if(empty($company_id)){
            $form->addError('Your company doesn\'t exist. Please choose another one.');
            return;
        }
        //save form values
        $table = Engine_Api::_()->getDbtable('blocks','webmix');
        $db = $table->getAdapter();
        $db->beginTransaction();
        try{
            $block = Engine_Api::_()->getItem('webmix_block',$block_id);

            //get company_id old
            $company_old = $block->company_id;
            
            $block->company_id = $company_id;
            $block->save();
            $db->commit();
            
            if ($webmix->content_type != Webmix_Api_Core::WEBMIX_CONTENT_TYPE_MUSIC){
                //Call hook to set company add count
                $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCompanyAddCount', array(
                  'company' => $company_old,
                  'company_new' => $company_id,
                ));
            }
        }
        catch(Exception $e)
        {
            $db->rollback();
            throw $e;
        }
        
        
        $this->view->success = true;
        $this->view->webmix_id = $webmix_id;
        return;
        return $this->_forward('success', 'utility', 'core', array(
            'messages' => array('Your changes have been saved.'),
            'smoothboxClose' => 1000,
            'parentRedirect' => Zend_Controller_Front::getInstance()->getRouter()->assemble(array('action' => 'index','controller'=>'index','module'=>'webmix','webmix' => $webmix_id), 'default', true),
        ));                  
  }
  
  public function deleteAction()
  {
    $webmix_id = $this->_getParam('webmix',null);
    $id = $this->_getParam('block', null);
    $this->view->company = $block = Engine_Api::_()->getItem('webmix_block', $id);
    $this->view->form = $form = new Webmix_Form_Block_Delete();
    // deleting user
    //$form->user_id->setValue($id);

    if( !$this->getRequest()->isPost() ) {
        return;
    }
    
    $db = Engine_Api::_()->getDbtable('blocks', 'webmix')->getAdapter();
    $db->beginTransaction();
    
    try {
        
        $webmix = Engine_Api::_()->getItem('webmixes',$webmix_id);
        if ($webmix->content_type == Webmix_Api_Core::WEBMIX_CONTENT_TYPE_SAMPE )
        {
            //Call hook to set company add count
            $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCompanyAddCount', array(
              'company_delete' => $block->company_id,
            ));
            
        }
        else {
             $album = Engine_Api::_()->getItem('webmix_musicalbum',$block->company_id);
             if ($album){
                $album->add_count = $album->add_count - 1;
                $album->save();
             }
            
        }
                    
        $block->delete();
        
        $db->commit();
       
    } catch( Exception $e ) {
        $db->rollBack();
        throw $e;
    }
                
      $this->view->webmix_id = $webmix->webmix_id;
        
      $this->view->urlR = $this->view->url(array('module'=>'webmix','controller'=>'index','action'=>'index','webmix'=>$webmix->webmix_id),'default',true);
      return;

  }
    
  public function getCompanyAction(){
    $name = $this->_getParam('name');
    $id = $this->_getParam('id');
    $viewer = Engine_Api::_()->user()->getViewer();
    if(!$name && !$id){
        return;
    }
    
    $Company_table = Engine_Api::_()->getDbTable('companies','webmix');     
    //get Hint by company title
    if($name && $name != ""){
        $Country_table = Engine_Api::_()->getDbTable('countries','webmix');   
                
        $select = $Company_table->select()
                    ->setIntegrityCheck(false)
                    ->from('engine4_webmix_companies as company')
                    ->join('engine4_webmix_countries as country', 'country.country_id = company.country_id',array('country_id','key'))
            //Search for title and link           
                    ->where('company.title like ? OR company.link like ?',$name.'%')          
                    ->where('country.selected = 1')
                    ->where('company.type = "admin" OR (owner_id = ? AND company.approve = 0) OR (company.approve = 1 AND owner_id <> ?)',$viewer->getIdentity())
                    ;          
    }
    //get company (to fill) by company_id
    $companies = array();
    if($id){

        $select = $Company_table->select()
                    ->where('company_id = ?',$id.'%');
        $row = $Company_table->fetchAll($select)->getRow(0);
        
        $photo_url = $row->getPhotoUrl('thumb.normal');        
        
        $companies = array(
            'photo_url' => $photo_url,
        );                              
    }
                                            
    // if get company by id
   	$companies = array_merge($Company_table->fetchAll($select)->toArray(), $companies);     
    
    return $this->_helper->json($companies);
    $this->getResponse()->setBody(Zend_Json::encode($companies));
  }
   
}